package com.hontech.bvapp2.utils

import serial.toU8


private val HEX_LIST = arrayOf(
    '0', '1', '2', '3',
    '4', '5', '6', '7',
    '8', '9', 'a', 'b',
    'c', 'd', 'e', 'f'
)


fun ByteArray.toHex(): String {
    val len = this.size
    val sb = StringBuilder()
    for (i in 0 until len) {
        val v = this[i].toU8()
        sb.append(HEX_LIST[v shr 4])
        sb.append(HEX_LIST[v and 0x0F])
        if (i != (len - 1)) {
            sb.append(' ')
        }
    }
    return sb.toString()
}

fun ByteArray.formatMac(): String {
    val len = this.size
    val sb = StringBuilder()
    for (i in 0 until len) {
        val v = this[i].toU8()
        sb.append(HEX_LIST[v shr 4])
        sb.append(HEX_LIST[v and 0x0F])
        if (i != (len - 1)) {
            sb.append(':')
        }
    }
    return sb.toString()
}

fun Int.hex8(): String {
    val h = (this shr 4) and 0x0F
    val l = this and 0x0F

    return "${HEX_LIST[h]}${HEX_LIST[l]}"
}

fun Int.hex16(): String {
    val h0 = (this shr 12) and 0x0F
    val h1 = (this shr 8) and 0x0F
    val h2 = (this shr 4) and 0x0F
    val h3 = this and 0x0F
    return "${HEX_LIST[h0]}${HEX_LIST[h1]}${HEX_LIST[h2]}${HEX_LIST[h3]}"
}

fun Int.hex32(): String {
    val n = this shr 16
    val l = this and 0xFFFF
    return "${n.hex16()}${l.hex16()}"
}






